package net.jxtz.jxtzos.authentication.weixin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.jxtz.jxtzos.entity.auth.Role;
import net.jxtz.jxtzos.entity.auth.User;
import net.jxtz.jxtzos.entity.auth.WechatUser;
import net.jxtz.jxtzos.entity.auth.dto.WechatUserDto;
import net.jxtz.jxtzos.mapper.auth.UserMapper;
import net.jxtz.jxtzos.mapper.auth.WechatUserMapper;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 *
 * 获取用户信息
 *
 * @author a123
 */

@Slf4j
@Service
public class WechatUserDetailServiceImpl implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        WechatUserDto wechatUserDto = wechatUserMapper.getWechatUserByUnionId(s);
        if (Objects.isNull(wechatUserDto)){
            String error = s + "==> 绑定用户不存在";
            log.error(error);
            throw new UsernameNotFoundException(error);
        }


        List<Role> rolesByUserId = userMapper.getRolesByUserId(wechatUserDto.getUserId());
        Set<SimpleGrantedAuthority> authorities = new HashSet<>();
        rolesByUserId.forEach(role -> {
            String roleName = role.getRoleName();
            authorities.add(new SimpleGrantedAuthority("ROLE_" + roleName));
        });

        // 返回封装好的UserDetails
        log.info("微信用户信息封装完毕");
        return new WechatUserDetails(wechatUserDto.getUserId(), wechatUserDto.getUserName(), wechatUserDto.getUnionId(), authorities);
    }


    private UserMapper userMapper;

    private WechatUserMapper wechatUserMapper;

    @Autowired
    public void setWechatUserMapper(WechatUserMapper wechatUserMapper){
        this.wechatUserMapper = wechatUserMapper;
    }

    @Autowired
    public void setUserMapper(UserMapper userMapper){
        this.userMapper = userMapper;
    }
}
